package com.hellohoper.cloud.starter.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by hk on 16/11/28.
 */

@EnableConfigurationProperties(ZookeeperProperties.class)
@ConditionalOnClass({CuratorFramework.class})
public class ZookeeperAutoConfiguration {

    @Autowired
    private ZookeeperProperties zookeeperProperties;

    @Bean
    public CuratorFramework curatorFramework() throws Exception {
        CuratorFramework framework = CuratorFrameworkFactory.builder().
                namespace(zookeeperProperties.getNamespace()).
                connectString(zookeeperProperties.getConnectString()).
                sessionTimeoutMs(zookeeperProperties.getSessionTimeout()).
                connectionTimeoutMs(zookeeperProperties.getConnectionTimeout()).
                retryPolicy(new RetryNTimes(zookeeperProperties.getRetryNTimes(), zookeeperProperties.getRetryTime())).
                build();
        framework.start();
//        Stat stat = framework.checkExists().forPath(zookeeperProperties.getWorkspace());
//        if (zookeeperProperties.getWorkspace() != null && stat == null) {
//            framework.create().withMode(CreateMode.PERSISTENT).forPath(zookeeperProperties.getWorkspace());
//        }
        return framework;
    }
}
